package com.iris.live.services.services.impl;

import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.ApiForLiveService;
import com.iris.live.services.services.ApprovalService;
import com.iris.live.services.vo.RegionVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ThinkPad on 2016/9/5.
 */
@Service
public class ApiForLiveServiceImpl implements ApiForLiveService {

    private static Logger logger = LoggerFactory.getLogger(ApiForLiveServiceImpl.class);

    @Autowired
    private 用户Repository repository用户;
    @Autowired
    private ApiForLiveRepository apiForLiveRepository;
    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;
    @Autowired
    private Lsh车型Repository Lsh车型Repository;
    @Autowired
    private Lsh库存表Repository lsh库存表Repository;
    @Autowired
    private RoleItemRepository roleItemRepository;
    @Autowired
    private Lsh金融设置Repository lsh金融设置Repository;
    @Autowired
    private Lsh先享后选设置Repository lsh先享后选设置Repository;
    @Autowired
    private LSH金融设置适用车型Repository lSH金融设置适用车型Repository;
    @Autowired
    private RegionDirectoryRepository RegionDirectoryRepository;

    //分割逗号返回string数组
    public static String[] getStringArr(String str) {
        if (str.contains(",")) {
            String[] arr = str.split(",");
            return arr;
        } else {
            return new String[]{str};
        }
    }

    /**
     * 获取本店可可以接待人员
     *
     * @param permit
     * @return
     */
    @Override
    public List getAvailableUser(String permit) {
        return apiForLiveRepository.getAvailableUser(permit);
    }

    @Override
    public List getAvailableUser(String permit, String status) {
        return apiForLiveRepository.getAvailableUsers(permit, status);
    }

    /**
     * 获取本店，选取角色可使用功能
     *
     * @param permit
     * @param roleName
     * @return
     */
    @Override
    public List getAvailablePermissions(String permit, String roleName) {
        return apiForLiveRepository.getAvailablePermissions(permit, roleName);
    }

    /**
     * 根据主键查询出未删除的经销商
     *
     * @param permit
     * @return
     */
    @Override
    public List getLshDistributorByPermit(String permit) {
        return apiForLiveRepository.getLshDistributorByPermit(permit);
    }

    /**
     * 获取车型详细不为空的LSH车型list
     *
     * @return
     */
    @Override
    public List getLshCarNotBlank() {
        return apiForLiveRepository.getLshCarNotBlank();
    }

    /**
     * 根据传入的用户名和密码验证登陆
     *
     * @param userName
     * @param pwd
     * @return
     */
    @Override
    public Map validateLoginByUserNameAndPwd(String permit, String userName, String pwd,Integer groupType) {
        Map map = new HashMap();
        用户Model model = repository用户.findActiveUserNoPermit(userName, pwd);
        if (model == null) {
            map.put("respMsg", "用户名或密码错误");
            map.put("respCode", "validateError");
            map.put("许可", "");
            map.put("许可_BMBS", "");
            map.put("角色", "");
            map.put("职位", "");
            map.put("经销商名", "");
            map.put("经销商名_EN", "");
            return map;
        }
        //根据传入的用户名，密码，判断是否可以登录，可以的话，返回用户表的经销商许可，角色，职位,
        // 经销商表的利星行许可，经销商名，经销商名_EN
        if ("Admin".equals(model.get用户名())){
            map.put("respMsg", "");
            map.put("respCode", "");
            map.put("许可", model.get许可());
            map.put("许可_BMBS", model.get许可());
            map.put("角色", model.get角色());
            map.put("职位", model.get职位());
            map.put("经销商名", model.get角色());
            map.put("经销商名_EN", model.get角色());
            return map;
        }

        String role;
        Map userInfo;

        role = model.get角色();
        Map levelInfo = apiForLiveRepository.getGroupRoleInInfo(role);
        if(levelInfo != null){
            role = levelInfo.get("roleLevel").toString();
        }

        if(logger.isDebugEnabled()){
            logger.debug("role={}", role);
        }

        //判断是否是集团的账号：角色是集团、大区、小区、CTA、TJLS
       if ("集团".equals(model.get角色()) || "大区".equals(model.get角色()) ||  null != groupType ||
                "小区".equals(model.get角色()) || "CTA".equals(model.get角色()) ||
                "TJLS".equals(model.get角色())) {
            map.put("respMsg", "");
            map.put("respCode", "");
            map.put("许可", model.get许可());
            map.put("许可_BMBS", model.get许可());
            map.put("角色", role);
            map.put("职位", model.get职位());
            map.put("经销商名", model.get角色());
           map.put("经销商名_EN", model.get角色());
            return map;
        } else {
            Lsh经销商表Model lshModel = lsh经销商表Repository.findOne(model.get许可());
            map.put("respMsg", "");
            map.put("respCode", "");
            map.put("许可", lshModel.getLsh());
            map.put("许可_BMBS", lshModel.getBmbs());
            map.put("角色", model.get角色());
            map.put("职位", model.get职位());
            map.put("经销商名", lshModel.get经销商名());
            map.put("经销商名_EN", lshModel.get经销商名en());
            return map;
        }
    }

    /**
     * 根据车架号查询到GP1、GP2、GP3
     */
    @Override
    public Map getGPByVin(String vinList) {
        Map map = new HashMap();
        if (vinList.contains(",")) {
            String[] arr = vinList.split(",");
            for (int i = 0; i < arr.length; i++) {
                String vin = arr[i];
                Map gpMap = apiForLiveRepository.getGPByVin(vin);
                map.put(arr[i], gpMap);
            }
            return map;
        }
        Map gpMapOne = apiForLiveRepository.getGPByVin(vinList);
        return gpMapOne;
    }

    @Override
    public PageData getStoreListByPermit(GetPermitRequest request, String permit) {
        return null;
    }

    @Override
    public PageData getStoreListByPermit(Map map, String license, RequestBase req) {
        List<Lsh库存表Model> list = new ArrayList<>();
        //获取本店的大区，小区，CTA等信息，理论上一个经销商名可以对应多个许可，但是只能有一个CTA，小区，大区
        List<Lsh经销商表Model> list本店 = lsh经销商表Repository.findAllPermitBy本店1(license);
        Lsh经销商表Model entity本店 = list本店.get(0);
        String param = (String) map.get("param");//获取出他店参数
        String[] arr = getStringArr(param);//如:东一区，东二区
        for (int m = 0; m < arr.length; m++) {
            List<Lsh经销商表Model> list许可 = null;
            Lsh经销商表Model area = lsh经销商表Repository.findAreaByParam(arr[m]).get(0);
            String area大区 = area.get大区();
            String area小区 = area.get小区();
            String areaCTA = area.getCta();
            String area经销商名 = area.get经销商名();

            if (arr[m].equals(area大区)) {
                //获取大区下所有的许可
                list许可 = lsh经销商表Repository.findAllPermitBy大区(area大区);
            }
            if (arr[m].equals(area小区)) {
                //获取小区下所有的许可
                list许可 = lsh经销商表Repository.findAllPermitBy小区(area小区);
            }
            if (arr[m].equals(areaCTA)) {
                //获取CTA下所有的许可
                list许可 = lsh经销商表Repository.findAllPermitByCTA(areaCTA);
            }
            if (arr[m].equals(area经销商名)) {
                //获取他店的许可
                list许可 = lsh经销商表Repository.findAllPermitBy他店(area经销商名);
            }
            //取出每个他店的许可
            List <String>nationwidePermit=new ArrayList<>();
            List <String>bigPermit=new ArrayList<>();
            List <String>smallPermit=new ArrayList<>();
            List <String>noSee=new ArrayList<>();
          for (int i = 0; i < list许可.size(); i++) {
                Lsh经销商表Model entity他店 = list许可.get(i);
                if (entity本店.get大区()!=null&&!entity本店.get大区().equals(entity他店.get大区())) {
                    nationwidePermit.add(entity他店.getBmbs());
                    // List<Lsh库存表Model> list1 = lsh库存表Repository.getCarsByPermit1(entity他店.getBmbs(), "全国可见");
                    //   List list11 = apiForLiveRepository.getCarsByPermit1(entity他店.getBmbs(), "全国可见", map);
                    // list.addAll(list11);
                }
                if (entity本店.get小区() != null) {
                    if (entity本店.get大区().equals(entity他店.get大区()) && !entity本店.get小区().equals(entity他店.get小区())) {
                        bigPermit.add(entity他店.getBmbs());
                        //  List<Lsh库存表Model> list2 = lsh库存表Repository.getCarsByPermit2(entity他店.getBmbs(), "全国可见", "大区可见");
                        //   List list22 = apiForLiveRepository.getCarsByPermit1(entity他店.getBmbs(), "全国大区可见", map);
                        //   list.addAll(list22);
                    }
                }
                if (entity他店.get小区() != null && entity本店.getCta() != null) {
                    if (entity本店.get大区().equals(entity他店.get大区()) && entity本店.get小区().equals(entity他店.get小区()) &&
                            !entity本店.getCta().equals(entity他店.getCta())) {
//                        List<Lsh库存表Model> list3 = lsh库存表Repository.getCarsByPermit3(entity他店.getBmbs(), "全国可见",
//                                "大区可见", "小区可见");
                        smallPermit.add(entity他店.getBmbs());
                        //  List list33 = apiForLiveRepository.getCarsByPermit1(entity他店.getBmbs(), "全国大区小区可见", map);
                        //  list.addAll(list33);
                    }
                }

                if (entity本店.getCta() != null) {
                    if (entity本店.get大区().equals(entity他店.get大区()) && entity本店.get小区().equals(entity他店.get小区()) &&
                            entity本店.getCta().equals(entity他店.getCta()) && !entity本店.get经销商名().equals(entity他店.get经销商名())) {
                        // List<Lsh库存表Model> list4 = lsh库存表Repository.getCarsByPermit4(entity他店.getBmbs());
                        noSee.add(entity他店.getBmbs());
                      //  List list44 = apiForLiveRepository.getCarsByPermit1(entity他店.getBmbs(), "外部不可见", map);
                       // list.addAll(list44);
                    }
                }
            }
            if(nationwidePermit.size()!=0) {
                List list11 = apiForLiveRepository.getCarsByPermit1(nationwidePermit, "全国可见", map);
                list.addAll(list11);
            }
            if(bigPermit.size()!=0) {
            List list22 = apiForLiveRepository.getCarsByPermit1(bigPermit, "全国大区可见", map);
            list.addAll(list22);
            }
                if(smallPermit.size()!=0) {
            List list33 = apiForLiveRepository.getCarsByPermit1(smallPermit, "全国大区小区可见", map);
            list.addAll(list33);
                }
                    if(noSee.size()!=0) {
            List list44 = apiForLiveRepository.getCarsByPermit1(noSee, "外部不可见", map);
            list.addAll(list44);
                    }
        }
        //手动分页
        PageData data = new PageData(new ArrayList(), 0);
        data.setTotal(list.size());
        List result = new ArrayList();
        if (req.getPageSize() == 0 && req.getPageIndex() == 0) {
            data.setData(list);
            return data;
        }
        Integer size = (req.getPageIndex() + 1) * req.getPageSize();
        if (size > list.size()) {
            size = list.size();
        }
        for (int i = req.getPageIndex() * req.getPageSize(); i < size; i++) {
            result.add(list.get(i));
        }
        data.setData(result);
        return data;
    }

    @Override
    public List getNowTime() {
        return apiForLiveRepository.getNowTime();
    }

    @Override
    public boolean isSetPermit(String permit) {
        List<RoleItemModel> list = roleItemRepository.isSetPermit(permit);
        return list.size() > 0 ? true : false;
    }

    @Override
    public List getLatestUpdatetimeByPermit(String permit) {
        return apiForLiveRepository.getLatestUpdatetimeByPermit(permit);
    }

    @Override
    public PageData getBenzRental(GetBenzRentalRequst req) {
        return apiForLiveRepository.getBenzRental(req);
    }

    @Override
    @Transactional
    public boolean savaBenzBatch(List<SavaBenzBatchRequest> reqList, String license, String userName) {
        Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
        Integer insNum = 2;//金融机构编号为2
        try {
            for (int i = 0; i < reqList.size(); i++) {
                SavaBenzBatchRequest s = reqList.get(i);
                //判断表中数据是否存在
                List listStar = apiForLiveRepository.getBenzRental(s.开始日期.toString(), s.结束日期.toString(), 0, s.value1, s.车型编号);
                List listCommon = apiForLiveRepository.getBenzRental(s.开始日期.toString(), s.结束日期.toString(), 1, s.value3, s.车型编号);
                int type = 0;
                int type2 = 0;
                if (listStar.size() > 0) {
                    type = 1;
                }
                if (listCommon.size() > 0) {
                    type2 = 1;
                }
                //1、保存LSH金融设置
                if (type == 1 && type2 == 1)
                    continue;
                Lsh金融设置Model set = new Lsh金融设置Model();
                set.set金融机构编号(insNum);
                set.set开始日期(s.开始日期);
                set.set结束日期(s.结束日期);
                set.set年利率(null);
                //插入 `lsh金融设置` 默认值: 费率状态: 利率, 是否固定 = '是', 业务类型 = '汽车分期',
                // 按揭类型 = '先享后选', 贴息类型 = '非贴息', 是否热销 = '否', 是否有效 = '是', 是否删除 = '否'
                set.set利率状态("利率");
                set.set期数(null);
                set.set是否固定("是");
                set.set业务类型("汽车分期");
                set.set按揭类型("先享后选");
                set.set贴息类型("非贴息");
                set.set是否热销("否");
                set.set是否有效("是");
                set.set是否删除("否");
                set.set更新时间(ts);
                set.set许可(license);
                set.set更新账号(userName);
                set.set金融系列("1");
                set.set产品编码(s.产品编号);
                Lsh金融设置Model model金融设置 = lsh金融设置Repository.save(set);

                //2、保存lsh先享后选(12个)
                Lsh先享后选设置Model a = new Lsh先享后选设置Model();
                Lsh先享后选设置Model b = new Lsh先享后选设置Model();
                Lsh先享后选设置Model c = new Lsh先享后选设置Model();
                Lsh先享后选设置Model d = new Lsh先享后选设置Model();
                Lsh先享后选设置Model e = new Lsh先享后选设置Model();
                Lsh先享后选设置Model f = new Lsh先享后选设置Model();

                Lsh先享后选设置Model k = new Lsh先享后选设置Model();
                Lsh先享后选设置Model l = new Lsh先享后选设置Model();
                Lsh先享后选设置Model m = new Lsh先享后选设置Model();
                Lsh先享后选设置Model n = new Lsh先享后选设置Model();
                Lsh先享后选设置Model o = new Lsh先享后选设置Model();
                Lsh先享后选设置Model p = new Lsh先享后选设置Model();

                /*1W数据*/
                Lsh先享后选设置Model q = new Lsh先享后选设置Model();
                Lsh先享后选设置Model r = new Lsh先享后选设置Model();
                Lsh先享后选设置Model t = new Lsh先享后选设置Model();
                Lsh先享后选设置Model u = new Lsh先享后选设置Model();

                if (type != 1 && (s.value1 != null && !"".equals(s.value1))) {
                    a.set金融编号(model金融设置.get金融编号());
                    a.set期数(24);
                    a.set是否固定("是");
                    a.set年利率(s.value1);
                    a.set利率类型(0);
                    a.set保值比例(s.value5);
                    a.set保值金额(null);
                    a.set参数(15000);
                    a.set更新账号(userName);
                    a.set更新时间(ts);

                    lsh先享后选设置Repository.save(a);

                    b.set金融编号(model金融设置.get金融编号());
                    b.set期数(24);
                    b.set是否固定("是");
                    b.set年利率(s.value1);
                    b.set利率类型(0);
                    b.set保值比例(s.value6);
                    b.set保值金额(null);
                    b.set参数(20000);
                    b.set更新账号(userName);
                    b.set更新时间(ts);
                    lsh先享后选设置Repository.save(b);

                    c.set金融编号(model金融设置.get金融编号());
                    c.set期数(24);
                    c.set是否固定("是");
                    c.set年利率(s.value1);
                    c.set利率类型(0);
                    c.set保值比例(s.value7);
                    c.set保值金额(null);
                    c.set参数(25000);
                    c.set更新账号(userName);
                    c.set更新时间(ts);
                    lsh先享后选设置Repository.save(c);

                    k.set金融编号(model金融设置.get金融编号());
                    k.set期数(36);
                    k.set是否固定("是");
                    k.set年利率(s.value2);
                    k.set利率类型(0);
                    k.set保值比例(s.value8);
                    k.set保值金额(null);
                    k.set参数(15000);
                    k.set更新账号(userName);
                    k.set更新时间(ts);
                    lsh先享后选设置Repository.save(k);

                    l.set金融编号(model金融设置.get金融编号());
                    l.set期数(36);
                    l.set是否固定("是");
                    l.set年利率(s.value2);
                    l.set利率类型(0);
                    l.set保值比例(s.value9);
                    l.set保值金额(null);
                    l.set参数(20000);
                    l.set更新账号(userName);
                    l.set更新时间(ts);
                    lsh先享后选设置Repository.save(l);

                    m.set金融编号(model金融设置.get金融编号());
                    m.set期数(36);
                    m.set是否固定("是");
                    m.set年利率(s.value2);
                    m.set利率类型(0);
                    m.set保值比例(s.value10);
                    m.set保值金额(null);
                    m.set参数(25000);
                    m.set更新账号(userName);
                    m.set更新时间(ts);
                    lsh先享后选设置Repository.save(m);

                    q.set金融编号(model金融设置.get金融编号());
                    q.set期数(24);
                    q.set是否固定("是");
                    q.set年利率(s.value1);
                    q.set利率类型(0);
                    q.set保值比例(s.value11);
                    q.set保值金额(null);
                    q.set参数(10000);
                    q.set更新账号(userName);
                    q.set更新时间(ts);

                    lsh先享后选设置Repository.save(q);

                    r.set金融编号(model金融设置.get金融编号());
                    r.set期数(36);
                    r.set是否固定("是");
                    r.set年利率(s.value1);
                    r.set利率类型(0);
                    r.set保值比例(s.value12);
                    r.set保值金额(null);
                    r.set参数(10000);
                    r.set更新账号(userName);
                    r.set更新时间(ts);

                    lsh先享后选设置Repository.save(r);

                }

                if (type2 != 1 && s.value3 != null && !"".equals(s.value3)) {
                    d.set金融编号(model金融设置.get金融编号());
                    d.set期数(24);
                    d.set是否固定("是");
                    d.set年利率(s.value3);
                    d.set利率类型(1);
                    d.set保值比例(s.value5);
                    d.set保值金额(null);
                    d.set参数(15000);
                    d.set更新账号(userName);
                    d.set更新时间(ts);
                    lsh先享后选设置Repository.save(d);

                    e.set金融编号(model金融设置.get金融编号());
                    e.set期数(24);
                    e.set是否固定("是");
                    e.set年利率(s.value3);
                    e.set利率类型(1);
                    e.set保值比例(s.value6);
                    e.set保值金额(null);
                    e.set参数(20000);
                    e.set更新账号(userName);
                    e.set更新时间(ts);
                    lsh先享后选设置Repository.save(e);

                    f.set金融编号(model金融设置.get金融编号());
                    f.set期数(24);
                    f.set是否固定("是");
                    f.set年利率(s.value3);
                    f.set利率类型(1);
                    f.set保值比例(s.value7);
                    f.set保值金额(null);
                    f.set参数(25000);
                    f.set更新账号(userName);
                    f.set更新时间(ts);
                    lsh先享后选设置Repository.save(f);


                    n.set金融编号(model金融设置.get金融编号());
                    n.set期数(36);
                    n.set是否固定("是");
                    n.set年利率(s.value4);
                    n.set利率类型(1);
                    n.set保值比例(s.value8);
                    n.set保值金额(null);
                    n.set参数(15000);
                    n.set更新账号(userName);
                    n.set更新时间(ts);
                    lsh先享后选设置Repository.save(n);

                    o.set金融编号(model金融设置.get金融编号());
                    o.set期数(36);
                    o.set是否固定("是");
                    o.set年利率(s.value4);
                    o.set利率类型(1);
                    o.set保值比例(s.value9);
                    o.set保值金额(null);
                    o.set参数(20000);
                    o.set更新账号(userName);
                    o.set更新时间(ts);
                    lsh先享后选设置Repository.save(o);

                    p.set金融编号(model金融设置.get金融编号());
                    p.set期数(36);
                    p.set是否固定("是");
                    p.set年利率(s.value4);
                    p.set利率类型(1);
                    p.set保值比例(s.value10);
                    p.set保值金额(null);
                    p.set参数(25000);
                    p.set更新账号(userName);
                    p.set更新时间(ts);
                    lsh先享后选设置Repository.save(p);

                    t.set金融编号(model金融设置.get金融编号());
                    t.set期数(24);
                    t.set是否固定("是");
                    t.set年利率(s.value3);
                    t.set利率类型(1);
                    t.set保值比例(s.value11);
                    t.set保值金额(null);
                    t.set参数(10000);
                    t.set更新账号(userName);
                    t.set更新时间(ts);

                    lsh先享后选设置Repository.save(t);

                    u.set金融编号(model金融设置.get金融编号());
                    u.set期数(36);
                    u.set是否固定("是");
                    u.set年利率(s.value1);
                    u.set利率类型(1);
                    u.set保值比例(s.value12);
                    u.set保值金额(null);
                    u.set参数(10000);
                    u.set更新账号(userName);
                    u.set更新时间(ts);

                    lsh先享后选设置Repository.save(u);

                }


                //3.保存金融设置适用车型
                String[] arr = getStringArr(s.车型编号);
                for (int j = 0; j < arr.length; j++) {
                    Lsh金融设置适用车型Model lsh金融设置适用车型Model = new Lsh金融设置适用车型Model();
                    lsh金融设置适用车型Model.set金融编号(model金融设置.get金融编号());
                    lsh金融设置适用车型Model.set适用车型(Integer.valueOf(arr[j]));
                    lSH金融设置适用车型Repository.save(lsh金融设置适用车型Model);
                }

            }
        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("奔驰金融产品保存失败", e);
            return false;
        }
        return true;
    }

    @Override
    public List getAllArea(String permit) {
        return apiForLiveRepository.getAllArea(permit);
    }

    @Override
    public List getCusRecordByPhone(GetCusRecordByPhoneReq req) {
        return apiForLiveRepository.getCusRecordByPhone(req);
    }

    @Override
    public ResultData getCusFlowAndClueAndOrder(String license, GetCusFlowAndClueAndOrderReq req) {
        ResultData rd = new ResultData();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //获取当前月第一天
            Calendar c = Calendar.getInstance();
            //c.setTime(sdf.parse("2016-11-11"));//测试用，因为12月份没有数据
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
            String firstDate = sdf.format(c.getTime());

            //获取当前月最后一天
            Calendar ca = Calendar.getInstance();
            c.setTime(sdf.parse("2016-11-11"));
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String lastDate = sdf.format(ca.getTime());

            //当前日期
            String currDate = sdf.format(new Date());

            List list = new ArrayList();
            //获取本日月展厅客流数
            if ("客流".equals(req.param)) {
                if ("本日".equals(req.date)) {
                    list = apiForLiveRepository.getCusFlowByPermitAndDate(license, currDate, null, null);
                } else if ("本月".equals(req.date)) {
                    list = apiForLiveRepository.getCusFlowByPermitAndDate(license, null, firstDate, lastDate);
                }
            }

            //获取本日月进店线索数
            if ("进店线索数".equals(req.param)) {
                if ("本日".equals(req.date)) {
                    list = apiForLiveRepository.getClueByPermitAndDate(license, currDate, null, null);
                } else if ("本月".equals(req.date)) {
                    list = apiForLiveRepository.getClueByPermitAndDate(license, null, firstDate, lastDate);
                }
            }

            //获取本日月新增订单数
            if ("新增订单数".equals(req.param)) {
                if ("本日".equals(req.date)) {
                    list = apiForLiveRepository.getOrderByPermitAndDate(license, currDate, null, null);
                } else if ("本月".equals(req.date)) {
                    list = apiForLiveRepository.getOrderByPermitAndDate(license, null, firstDate, lastDate);
                }
            }
            rd.setResult("true");
            rd.setMessage("查询成功");
            rd.setPageData(new PageData(list, list.size()));
            return rd;

        } catch (Exception e) {
            logger.error("数据获取异常。", e);
            rd.setResult("false");
            rd.setMessage("服务器发生未知错误");
            rd.setPageData(null);
            return rd;
        }
    }

    @Override
    public ResultData getAllAreaAndPMA() {
        return apiForLiveRepository.getAllAreaAndPMA();
    }

    /**
     * 他店车辆查看
     * copy自上方 getStoreListByPermit 接口,把小区和CTA删了
     *
     * @param map
     * @param license
     * @param req
     * @return
     */
    @Override
    public PageData getOtherStoreInfoByPermit(Map map, String license, RequestBase req) {
        List<Lsh库存表Model> list = new ArrayList<>();
        //获取本店的大区，小区，CTA等信息，理论上一个经销商名可以对应多个许可，但是只能有一个CTA，小区，大区
        List<Lsh经销商表Model> list本店 = lsh经销商表Repository.findAllPermitBy本店1(license);
        Lsh经销商表Model entity本店 = list本店.get(0);
        String param = (String) map.get("param");//获取出他店参数
        String[] arr = getStringArr(param);//如:东一区，东二区
        for (int m = 0; m < arr.length; m++) {
            List<Lsh经销商表Model> list许可 = null;
            String a = arr[m];
            Lsh经销商表Model area = lsh经销商表Repository.findDCHAreaByParam(arr[m]).get(0);
            String area大区 = area.get大区();
            String area经销商名 = area.get经销商名();

            if (arr[m].equals(area大区)) {
                //获取大区下所有的许可
                list许可 = lsh经销商表Repository.findAllPermitBy大区(area大区);
            }
            if (arr[m].equals(area经销商名)) {
                //获取他店的许可
                list许可 = lsh经销商表Repository.findAllPermitBy他店(area经销商名);
            }
            //取出每个他店的许可
            List<String> nationwidePermit = new ArrayList<>();
            List<String> noSee = new ArrayList<>();
            for (int i = 0; i < list许可.size(); i++) {
                Lsh经销商表Model entity他店 = list许可.get(i);
                nationwidePermit.add(entity他店.getBmbs());
                if (entity本店.get经销商名() != null) {
                    noSee.add(entity他店.getBmbs());
                }
            }

            if (nationwidePermit.size() != 0) {
                List list11 = apiForLiveRepository.getCarsByPermit1(nationwidePermit, "全国可见", map);
                list.addAll(list11);
            }

            if (noSee.size() != 0) {
                List list44 = apiForLiveRepository.getCarsByPermit1(noSee, "外部不可见", map);
                list.addAll(list44);
            }
        }
        //手动分页
        PageData data = new PageData(new ArrayList(), 0);
        data.setTotal(list.size());
        List result = new ArrayList();
        if (req.getPageSize() == 0 && req.getPageIndex() == 0) {
            data.setData(list);
            return data;
        }
        Integer size = (req.getPageIndex() + 1) * req.getPageSize();
        if (size > list.size()) {
            size = list.size();
        }
        for (int i = req.getPageIndex() * req.getPageSize(); i < size; i++) {
            result.add(list.get(i));
        }
        data.setData(result);
        return data;
    }

    /**
     * 获取省市区地域目录信息  国家级别
     */
    @Override
    public List<RegionVO> getRegioncountry() {
        List<RegionVO> listvo = new ArrayList<>();
        RegionVO vo = new RegionVO();
        try {
            // 第一层级 国家
            RegionDirectoryModel country = new RegionDirectoryModel();
            List<RegionDirectoryModel> country1 = new ArrayList<>();
            country1 = RegionDirectoryRepository.getRegionAll();

            for (RegionDirectoryModel rd:country1) {
                if (rd.getId()==1){
                    vo.setId(rd.getId());
                    vo.setName(rd.getName());
                    vo.setNameEN(rd.getNameCn());
                    vo.setFatherId(rd.getPid());
                    vo.setType("0");
                    vo.setRegionList(getRegionProvince(rd.getId(),country1));
                    listvo.add(vo);
                }
            }
        }catch (Exception e){
            logger.error("获取省市区地域目录信息:“国家级别”失败",e);
        }
        return listvo;
    }

    /**
     * 获取省市区地域目录信息  省级别
     */
    public List<RegionVO> getRegionProvince(int id, List<RegionDirectoryModel> Province) {
        List<RegionVO> result = new ArrayList<>();
        try {
//            List<RegionDirectoryModel> Province = RegionDirectoryRepository.getRegionCity(fatherId);
            for (RegionDirectoryModel list:Province) {
                if (list.getPid()!=null && list.getPid()==id) {
                    RegionVO vo = new RegionVO();
                    vo.setId(list.getId());
                    vo.setName(list.getName());
                    vo.setNameEN(list.getNameCn());
                    vo.setFatherId(list.getPid());
                    vo.setType("1");

                    vo.setRegionList(getRegionCity(list.getId(),Province));
                    result.add(vo);
                }
            }

        }catch (Exception e){
            logger.error("获取省市区地域目录信息:“省级别”失败",e);
        }
        return result;
    }


    /**
     * 获取省市区地域目录信息  市级别
     */
    public List<RegionVO> getRegionCity(int fatherId,List<RegionDirectoryModel> City) {
        List<RegionVO> result = new ArrayList<>();
        try {
//            List<RegionDirectoryModel> City = RegionDirectoryRepository.getRegionCity(fatherId);
            for (RegionDirectoryModel list: City) {
                if (list.getPid()!=null && list.getPid()==fatherId) {
                    RegionVO vo = new RegionVO();
                    vo.setId(list.getId());
                    vo.setName(list.getName());
                    vo.setNameEN(list.getNameCn());
                    vo.setFatherId(list.getPid());
                    vo.setType("2");

                    vo.setRegionList(getRegionLevel(list.getId(),City));
                    result.add(vo);
                }
            }
        }catch (Exception e){
            logger.error("获取省市区地域目录信息:“市级别”失败",e);
        }
        return result;
    }
    /**
     * 获取省市区地域目录信息  区/县 级别
     */
    public List<RegionVO> getRegionLevel(int fatherId,List<RegionDirectoryModel> Level) {
        List<RegionVO> result = new ArrayList<>();
        try {
//            List<RegionDirectoryModel> Level = RegionDirectoryRepository.getRegionCity(fatherId);
            for (RegionDirectoryModel list: Level) {
                if (list.getPid()!=null && list.getPid()==fatherId) {
                    RegionVO vo = new RegionVO();
                    vo.setId(list.getId());
                    vo.setName(list.getName());
                    vo.setNameEN(list.getNameCn());
                    vo.setFatherId(list.getPid());
                    vo.setType("3");
                    // 没有下一级
                    vo.setRegionList(null);
                    result.add(vo);
                }
            }
        }catch (Exception e){
            logger.error("获取省市区地域目录信息:“区/县级别”失败",e);
        }
        return result;
    }
}
